package com.naizhuai.ui.adapter.business;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.naizhuai.R;
import com.naizhuai.ui.entity.ImageBean;
import com.naizhuai.ui.entity.mainbusiness.CompareImageBean;
import com.naizhuai.util.FileNameUtils;
import com.naizhuai.util.NaizhuAILog;
import com.yalantis.ucrop.callback.BitmapCropCallback;
import com.yalantis.ucrop.view.GestureCropImageView;
import com.yalantis.ucrop.view.TransformImageView;
import com.yalantis.ucrop.view.UCropView;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.Filter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by code_han on 2018/5/8.
 */

public class ActionContrastImagePagerAdapter extends PagerAdapter {
    private Activity mContext;
    private List<CompareImageBean> imageEditList;
    private PagerManageImageListener listener;


    public static final String PRE_GES_VIEW_KEY = "pre_ges_view_key";
    public static final String AFT_GES_VIEW_KEY = "aft_ges_view_key";

    private SparseArray<Map<String, GestureCropImageView>> gesImageMapList;

    private boolean canEditModel = true;


    public static final int NONE = 0;
    public static final int SCALE = 1;
    public static final int ROTATE = 2;
    public static final int ALL = 3;
    private int[] mAllowedGestures = new int[]{SCALE, ROTATE, ALL};

    private int resetPosition = -1;

    private Bitmap.CompressFormat mCompressFormat = DEFAULT_COMPRESS_FORMAT;

    public static final int DEFAULT_COMPRESS_QUALITY = 90;

    public static final Bitmap.CompressFormat DEFAULT_COMPRESS_FORMAT = Bitmap.CompressFormat.JPEG;


    public ActionContrastImagePagerAdapter(Activity context, List<CompareImageBean> imageEditList, PagerManageImageListener listener) {
        this.mContext = context;
        this.imageEditList = imageEditList;
        this.listener = listener;
        gesImageMapList = new SparseArray<>();
    }

    @Override
    public int getCount() {
        return imageEditList.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        ViewHolder holder = (ViewHolder) container.getTag(position);
        View view;
        if (holder == null) {
            view = View.inflate(mContext, R.layout.adapter_action_edit_contract_image, null);
            holder = new ViewHolder();
            holder = initViewHolder(holder, view, position);
            holder.setView(view);
        } else {
            view = holder.getView();
        }
        if (imageEditList.size() > 0) {
            getAdapterView(position, holder);
        }
        container.addView(view);
        return view;
    }

    class ViewHolder {
        UCropView preEditImage;
        GestureCropImageView preGestureImageView;

        UCropView aftEditImage;

        RelativeLayout imageLayout;
        TextView changeUploadView;

        private View view;

        public View getView() {
            return view;
        }

        public void setView(View view) {
            this.view = view;
        }
    }

    private void getAdapterView(int position, ViewHolder holder) {
        ImageBean imageBefore = imageEditList.get(position).getBeforeImage();
        ImageBean imageAfter = imageEditList.get(position).getAfterImage();
//        GestureCropImageView aftGestureImageView;
        try {
            if (imageBefore != null && imageBefore.getImageUriInput() != null) {
                holder.preEditImage.setUserScrollEvent(true);
                holder.preEditImage.getOverlayView().setShowCropGrid(false);
                if (gesImageMapList.get(position) != null)
                    gesImageMapList.get(position).put(PRE_GES_VIEW_KEY, holder.preGestureImageView);
                else {
                    Map<String, GestureCropImageView> gesImageMap = new HashMap<>();
                    gesImageMap.put(PRE_GES_VIEW_KEY, holder.preGestureImageView);
                    gesImageMapList.put(position, gesImageMap);
                }
                holder.preGestureImageView.setImageUri(imageBefore.getImageUriInput(), imageBefore.getImageUriOutput());
            } else {
                holder.preEditImage.setUserScrollEvent(false);
            }
            if (imageAfter != null && imageAfter.getImageUriInput() != null) {
                refreshAftImage(holder, position, imageAfter);
//                holder.aftEditImage.setUserScrollEvent(true);
//                if (resetPosition == position) {
//                    holder.aftEditImage.resetCropImageView();
//                    resetPosition = -1;
//                }
//                aftGestureImageView = holder.aftEditImage.getCropImageView();
//                if (gesImageMapList.get(position) == null) {
//                    Map<String, GestureCropImageView> gesImageMap = new HashMap<>();
//                    gesImageMap.put(AFT_GES_VIEW_KEY, aftGestureImageView);
//                    gesImageMapList.put(position, gesImageMap);
//                } else {
//                    gesImageMapList.get(position).put(AFT_GES_VIEW_KEY, aftGestureImageView);
//                }
//                initGestureCropImageView(aftGestureImageView, holder.aftEditImage);
//                aftGestureImageView.setImageUri(imageAfter.getImageUriInput(), imageAfter.getImageUriOutput());
//                holder.imageLayout.setVisibility(View.GONE);
//                holder.changeUploadView.setVisibility(View.VISIBLE);
            } else {
                holder.aftEditImage.setUserScrollEvent(false);
                holder.aftEditImage.getOverlayView().setShowCropGrid(false);
                holder.imageLayout.setVisibility(View.VISIBLE);
                holder.changeUploadView.setVisibility(View.GONE);
            }
        } catch (Exception ignored) {
        }
    }

    private void refreshAftImage(ViewHolder holder, int position, ImageBean imageAfter) {
        holder.aftEditImage.setUserScrollEvent(true);
        holder.aftEditImage.getOverlayView().setShowCropGrid(false);
        if (resetPosition == position) {
            holder.aftEditImage.resetCropImageView();
            resetPosition = -1;
        }
        GestureCropImageView aftGestureImageView = holder.aftEditImage.getCropImageView();
        if (gesImageMapList.get(position) == null) {
            Map<String, GestureCropImageView> gesImageMap = new HashMap<>();
            gesImageMap.put(AFT_GES_VIEW_KEY, aftGestureImageView);
            gesImageMapList.put(position, gesImageMap);
        } else {
            gesImageMapList.get(position).put(AFT_GES_VIEW_KEY, aftGestureImageView);
        }
        initGestureCropImageView(aftGestureImageView, holder.aftEditImage);
        try {
            aftGestureImageView.setImageUri(imageAfter.getImageUriInput(), imageAfter.getImageUriOutput());
        } catch (Exception e) {
            e.printStackTrace();
        }
        holder.imageLayout.setVisibility(View.GONE);
        holder.changeUploadView.setVisibility(View.VISIBLE);
    }

    private ViewHolder initViewHolder(ViewHolder holder, View view, int position) {
        holder.preEditImage = view.findViewById(R.id.pre_crop_image);
        holder.preGestureImageView = holder.preEditImage.getCropImageView();

        holder.aftEditImage = view.findViewById(R.id.after_crop_image);


        holder.imageLayout = view.findViewById(R.id.add_image_layout);
        TextView uploadView = view.findViewById(R.id.upload_image);
        holder.changeUploadView = view.findViewById(R.id.change_upload_image);
        ImageView textImage = view.findViewById(R.id.text_image);

        initGestureCropImageView(holder.preGestureImageView, holder.preEditImage);

        uploadView.setOnClickListener(new UploadImageClickListener(position, holder));
        holder.changeUploadView.setOnClickListener(new UploadImageClickListener(position, holder));
        return holder;
    }

    @Override
    public void destroyItem(ViewGroup collection, int position, Object view) {
        collection.removeView((View) view);
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    public interface PagerManageImageListener {
        void uploadImage(ImageBean s, int position);

        void emptyImageError();

        void downloadImageError(Throwable e);

        void onLoadTransComplete();

        void onLoadTransFailure(@NonNull Exception e);

        void onTransRotate(float currentAngle);

        void onTransScale(float currentScale);

        void cropImage(Uri cropUri, int position, String cropPosition);

        void cropImagesFinished();

        void cropImageErrer(Throwable t, int position);

        void loadWrongFile(String wrongType);
    }

    class UploadImageClickListener implements View.OnClickListener {

        private int position;
        private ViewHolder holder;


        public UploadImageClickListener(int position, ViewHolder holder) {
            this.position = position;
            this.holder = holder;
        }

        @Override
        public void onClick(View v) {
            Album.image(mContext) // 选择图片。
                    .singleChoice()
                    .requestCode(200)
                    .camera(true)
                    .columnCount(3)
                    .onResult(new Action<ArrayList<AlbumFile>>() {
                        @Override
                        public void onAction(int requestCode, @NonNull ArrayList<AlbumFile> result) {
                            NaizhuAILog.e("chose url=" + result.get(0).getPath());
                            if (!FileNameUtils.isSuitableType(result.get(0).getPath(), "JPEG", "jpg", "png")) {
                                listener.loadWrongFile(FileNameUtils.getFileType(result.get(0).getPath()));
                                return;
                            }
                            ImageBean bean = new ImageBean();
                            bean.setImageUriInput(FileNameUtils.filePath2Uri(result.get(0).getPath()));
                            bean.setImageUriOutput(FileNameUtils.getCacheUri(result.get(0).getName(), mContext));
                            resetPosition = position;
                            refreshAftImage(holder, position, bean);
                            listener.uploadImage(bean, position);
                        }
                    }).start();
        }
    }

    private volatile int cropCount = 0;

    private boolean cropAndSaveSingleImage(GestureCropImageView gestView, int position, String imagePosition) {
        if (gestView == null)
            return false;
        gestView.cropAndSaveImage(mCompressFormat, DEFAULT_COMPRESS_QUALITY, new BitmapCropCallback() {

            @Override
            public void onBitmapCropped(@NonNull Uri resultUri, int offsetX, int offsetY, int imageWidth, int imageHeight) {
                listener.cropImage(resultUri, position, imagePosition);
                cropCount++;
                if (cropCount == gesImageMapList.size() * 2)
                    listener.cropImagesFinished();
            }

            @Override
            public void onCropFailure(@NonNull Throwable t) {
                listener.cropImageErrer(t, position);
            }
        });
        return true;
    }


    public void cropAndSaveImages() {
        cropCount = 0;
        for (int index = 0; index < gesImageMapList.size(); index++) {
            if (!cropAndSaveSingleImage(gesImageMapList.get(index).get(PRE_GES_VIEW_KEY), index, PRE_GES_VIEW_KEY)) {
                listener.emptyImageError();
                return;
            }
            if (!cropAndSaveSingleImage(gesImageMapList.get(index).get(AFT_GES_VIEW_KEY), index, AFT_GES_VIEW_KEY)) {
                listener.emptyImageError();
                return;
            }
        }
    }

    class TransImageListener implements TransformImageView.TransformImageListener {
        private UCropView editImage;

        public TransImageListener(UCropView editImage) {
            this.editImage = editImage;
        }

        @Override
        public void onLoadComplete() {
            editImage.animate().alpha(1).setDuration(300).setInterpolator(new AccelerateInterpolator());
            listener.onLoadTransComplete();
        }

        @Override
        public void onLoadFailure(@NonNull Exception e) {
            listener.onLoadTransFailure(e);
        }

        @Override
        public void onRotate(float currentAngle) {
            listener.onTransRotate(currentAngle);
        }

        @Override
        public void onScale(float currentScale) {
            listener.onTransScale(currentScale);
        }
    }

    private void initGestureCropImageView(GestureCropImageView gestView, UCropView view) {
        gestView.setCanTouchAndMove(canEditModel);
        gestView.setTransformImageListener(new TransImageListener(view));
        setAllowedGestures(gestView, 0);
    }

    private void setAllowedGestures(GestureCropImageView gesImage, int tab) {
        gesImage.setScaleEnabled(mAllowedGestures[tab] == ALL || mAllowedGestures[tab] == SCALE);
        gesImage.setRotateEnabled(mAllowedGestures[tab] == ALL || mAllowedGestures[tab] == ROTATE);
    }


    public void stopCropVIew() {
        for (int index = 0; index < gesImageMapList.size(); index++) {
            Map<String, GestureCropImageView> gesImageMap = gesImageMapList.get(index);
            for (GestureCropImageView image : gesImageMap.values()) {
                if (image != null)
                    image.cancelAllAnimations();
            }
        }
    }
}
